package com.miyuan.view.mine;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.miyuan.R;
import com.miyuan.base.BaseActivity;
import com.miyuan.bean.ResultBean;
import com.miyuan.bean.request.MachineListParam;
import com.miyuan.bean.request.UserReplenishmentParam;
import com.miyuan.bean.respone.GoodsListBean;
import com.miyuan.bean.respone.MachineListBean;
import com.miyuan.bean.respone.UserBean;
import com.miyuan.bean.respone.UserReplenishmentBean;
import com.miyuan.net.NetService;
import com.miyuan.net.RetrofitClient;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.ex.loadmore.SimpleLoadMoreViewCreator;
import net.idik.lib.slimadapter.ex.loadmore.SlimMoreLoader;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 补货记录
 */

public class RecruitRecordActivity extends BaseActivity {
    @BindView(R.id.search_result_list)
    RecyclerView recyclerView;
    @BindView(R.id.search_edit_text)
    EditText searchEdit;

    @BindView(R.id.timeText)
    TextView timeText;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefreshLayout;

    public int current = 1;
    public String startTime = "";
    public String endTime = "";
    public int size = 200;
    public String parameter = "";
    SlimAdapter slimAdapter;
    private boolean hasMore = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setLayout(R.layout.activity_recruit_record);
        super.onCreate(savedInstanceState);
        initList(new ArrayList());
        requestReplenishList();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        timeText.setText(format.format(new Date()));
        searchEdit.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    parameter = searchEdit.getText().toString().trim();
                    current = 1;
                    requestReplenishList();
                }
                return false;
            }
        });
    }

    public void requestReplenishList() {
        RetrofitClient.getInstance()
                .create(NetService.class)
                .getUserReplenishmentList(new UserReplenishmentParam(current, endTime, parameter, size, startTime).toRequestBody())
                .enqueue(new Callback<ResultBean<UserReplenishmentBean>>() {

                    @Override
                    public void onResponse(Call<ResultBean<UserReplenishmentBean>> call, Response<ResultBean<UserReplenishmentBean>> response) {
                        swipeRefreshLayout.setRefreshing(false);
                        ResultBean<UserReplenishmentBean> resultBean = response.body();
                        if (resultBean.getData() != null) {
                            slimAdapter.updateData(resultBean.getData().getRecords());
                            int listSize = resultBean.getData().getRecords().size();
                            hasMore = listSize >= size;
                        } else {
                            Toast.makeText(RecruitRecordActivity.this, resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResultBean<UserReplenishmentBean>> call, Throwable t) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    private void initList(List list) {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(RecruitRecordActivity.this);
        linearLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        slimAdapter = SlimAdapter.create().register(R.layout.item_recruit_record, new SlimInjector<UserReplenishmentBean.RecordsBean>() {
            @Override
            public void onInject(UserReplenishmentBean.RecordsBean data, IViewInjector injector) {
                injector.text(R.id.time, data.getReplenishmentTime());
                injector.text(R.id.machine_code, data.getNumber());
                injector.text(R.id.replenish_code, data.getNumbers());

                injector.image(R.id.img, R.mipmap.machine_default);
            }
        }).enableLoadMore(new SlimMoreLoader(RecruitRecordActivity.this, new SimpleLoadMoreViewCreator(RecruitRecordActivity.this).setNoMoreHint("").setLoadingHint("").setPullToLoadMoreHint("")) {
            @Override
            protected void onLoadMore(final Handler handler) {
                ++current;
                RetrofitClient.getInstance()
                        .create(NetService.class)
                        .getUserReplenishmentList(new UserReplenishmentParam(current, endTime, parameter, size, startTime).toRequestBody())
                        .enqueue(new Callback<ResultBean<UserReplenishmentBean>>() {

                            @Override
                            public void onResponse(Call<ResultBean<UserReplenishmentBean>> call, Response<ResultBean<UserReplenishmentBean>> response) {
                                swipeRefreshLayout.setRefreshing(false);
                                ResultBean<UserReplenishmentBean> resultBean = response.body();
                                if (resultBean.getData() != null) {
                                    handler.loadCompleted(resultBean.getData().getRecords());
                                    int listSize = resultBean.getData().getRecords().size();
                                    hasMore = listSize >= size;
                                } else {
                                    Toast.makeText(RecruitRecordActivity.this, resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<ResultBean<UserReplenishmentBean>> call, Throwable t) {
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        });
            }

            @Override
            protected boolean hasMore() {
                return hasMore;
            }
        }).attachTo(recyclerView);
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                current = 1;
                requestReplenishList();
            }
        });
        slimAdapter.updateData(list);
    }

    @OnClick(R.id.search_date)
    void selectDate() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(RecruitRecordActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                Toast.makeText(RecruitRecordActivity.this, date.toString(), Toast.LENGTH_SHORT).show();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                timeText.setText(format.format(date));
                startTime = format.format(date) + " 00:00:00";
                endTime = format.format(date) + " 23:59:59";
                current = 1;
                requestReplenishList();
            }
        }).build();
        pvTime.show();
    }

    @OnClick(R.id.back_layout)
    void pop() {
        finish();
    }
}
